package com.tcl.aota.admin.util;

import com.tcl.aota.admin.dto.Result;
import com.tcl.aota.common.constants.Constants;
import com.tcl.aota.common.utils.JsonParser;
import com.tcl.aota.persistent.model.Admin;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author kelong
 * @date 11/7/14
 */
public class SessionFilter implements Filter {
    Logger LOG = Logger.getLogger(SessionFilter.class);
    private static String loginPage = "/admin/login";
    private static Set<String> ignoreUrls = new HashSet<String>();
    private static String CONTEXTPATH = null;

    static {
        ignoreUrls.add("/admin/login");
        ignoreUrls.add("/admin/loginSys");
        ignoreUrls.add("/thirdApi/uploadApk");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String configIgnoreUrl = filterConfig.getInitParameter("config");
        if (!StringUtils.isEmpty(configIgnoreUrl)) {
            String[] urls = configIgnoreUrl.split(",");
            for (String url : urls) {
                ignoreUrls.add(url);
            }
        }
        CONTEXTPATH = filterConfig.getServletContext().getContextPath();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        String servletPath = servletRequest.getServletPath();
        if (ignoreUrls.contains(servletPath)) {
            filterChain.doFilter(request, response);
            return;
        }

        if (servletPath.matches(".+\\..+") && !servletPath.contains(".jsp")) {
            filterChain.doFilter(request, response);
            return;
        }
        Admin admin = RequestUtil.getSessionUser(servletRequest);
        //application/json, text/plain, */*
        if (admin == null) {
            LOG.info("user session is null or timeout!");
//            String ajax=servletRequest.getHeader("X-Requested-With");
            String acceptHeader=servletRequest.getHeader("Accept");
            if(acceptHeader!=null && acceptHeader.indexOf("application/json")!=-1){
                String code= JsonParser.toString(Result.get(null, Constants.Common.SESSION_OUT));
                servletResponse.getWriter().write(code);
                return;
            }
            servletResponse.sendRedirect(CONTEXTPATH + loginPage);
        } else {
            filterChain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {

    }
}
